import 'package:dio_wrapper/dio_wrapper.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_demo2/base/plugin/common_native.dart';
import 'package:flutter_demo2/dio_test/api_cost_interceptor.dart';
import 'package:flutter_demo2/home/unknown_page.dart';
import 'package:flutter_demo2/leak/leak_finder/lib/leak_observer.dart';
import 'package:flutter_demo2/pages.dart';
import 'package:logging/logging.dart';
import 'package:route/route.dart';

import 'base/plugin/route_native/manager.dart';
import 'base/route/page_stack_observer.dart';

void main() {
  RouterHelper.register();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    _initSomething();
    _finishSplash();
    super.initState();
  }

  bool _hasFinishSplash = false;

  void _finishSplash() {
    if (!_hasFinishSplash) {
      _hasFinishSplash = true;
      Future.delayed(const Duration(milliseconds: 500)).then((value) {
        commonNative.finishSplash();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo2',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // if use initialRoute, home will be invalidate, constructor params invalidate too.
      // home: AppEntry(key: _appEntryKey),
      initialRoute: FlutterPages.appEntryPage,
      navigatorObservers: [
        navObserver,
        if (kDebugMode) ...[
          LeakObserver(checkLeakDelay: 3),
        ]
      ],
      navigatorKey: navKey,
      onGenerateRoute: (settings) {
        return router.pageRoute(settings);
      },
    );
  }

  Future<bool> _isLogin() async {
    await Future.delayed(const Duration(milliseconds: 500));
    return false;
  }

  void _initSomething() {
    // Logger must be init or no use.
    // defaults to Level.INFO
    Logger.root.level = Level.INFO;
    Logger.root.onRecord.listen((record) {
      if (kDebugMode || kProfileMode) {
        debugPrint('${record.level.name}:${record.loggerName}: ${record.message}');
      }
    });
    // init route
    router.initRoute(
      pages,
      const UnknownPage(),
      topLevelPages: [
        FlutterPages.homePage,
        FlutterPages.historyPage,
        FlutterPages.settingPage,
        FlutterPages.mePage,
      ],
      initialRouteAddress: FlutterPages.appEntryPage,
      loginPageRouteAddress: FlutterPages.loginPage,
      checkLogin: _isLogin,
    );

    dio.init(
      // "https://jsonplaceholder.typicode.com/",
      "https://dog.ceo/api/",
      connectTimeout: 3000,
      receiveTimeout: 3000,
      defaultLogPrint: false,
      commonHeader: () {
        return {"initHead1": "initHead1", "initHead2": 2};
      },
    );
    dio.addInterceptor(ApiCostInterceptor());
  }
}
